import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { goodsApi } from '@/api/goods'
import { ElMessage } from 'element-plus'

export const useGoodsStore = defineStore('goods', () => {
  // 状态
  const goodsList = ref([])
  const currentGoods = ref(null)
  const myGoodsList = ref([])
  const categories = ref([
    { categoryId: 1, name: '电子产品', icon: '📱' },
    { categoryId: 2, name: '教材书籍', icon: '📚' },
    { categoryId: 3, name: '生活用品', icon: '🏠' },
    { categoryId: 4, name: '服装配饰', icon: '👕' },
    { categoryId: 5, name: '运动器材', icon: '⚽' },
    { categoryId: 6, name: '数码配件', icon: '🎧' },
    { categoryId: 7, name: '学习用品', icon: '✏️' },
    { categoryId: 8, name: '其他', icon: '📦' }
  ])
  const isLoading = ref(false)
  const pagination = ref({
    page: 1,
    limit: 20,
    total: 0
  })

  // 搜索条件
  const searchParams = ref({
    keyword: '',
    category: '',
    minPrice: '',
    maxPrice: '',
    condition: ''
  })

  // 计算属性
  const totalPages = computed(() => Math.ceil(pagination.value.total / pagination.value.limit))

  // 获取商品列表
  const getGoodsList = async (params = {}) => {
    try {
      isLoading.value = true
      const queryParams = {
        page: pagination.value.page,
        limit: pagination.value.limit,
        ...searchParams.value,
        ...params
      }
      
      const response = await goodsApi.getGoodsList(queryParams)
      
      if (response.code === 200) {
        goodsList.value = response.data.list
        pagination.value.total = response.data.total
        pagination.value.page = response.data.page
      } else {
        ElMessage.error(response.message || '获取商品列表失败')
      }
    } catch (error) {
      console.error('获取商品列表错误:', error)
      ElMessage.error('获取商品列表失败，请检查网络连接')
    } finally {
      isLoading.value = false
    }
  }

  // 获取商品详情
  const getGoodsDetail = async (goodsId) => {
    try {
      isLoading.value = true
      const response = await goodsApi.getGoodsDetail(goodsId)
      
      if (response.code === 200) {
        currentGoods.value = response.data
        return response.data
      } else {
        ElMessage.error(response.message || '获取商品详情失败')
        return null
      }
    } catch (error) {
      console.error('获取商品详情错误:', error)
      ElMessage.error('获取商品详情失败，请检查网络连接')
      return null
    } finally {
      isLoading.value = false
    }
  }

  // 发布商品
  const publishGoods = async (goodsData) => {
    try {
      isLoading.value = true
      const response = await goodsApi.publishGoods(goodsData)
      
      if (response.code === 200) {
        ElMessage.success('商品发布成功')
        return true
      } else {
        ElMessage.error(response.message || '商品发布失败')
        return false
      }
    } catch (error) {
      console.error('发布商品错误:', error)
      ElMessage.error('商品发布失败，请检查网络连接')
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 获取我的商品
  const getMyGoods = async (params = {}) => {
    try {
      isLoading.value = true
      const response = await goodsApi.getMyGoods(params)
      
      if (response.code === 200) {
        myGoodsList.value = response.data.list
        return response.data
      } else {
        ElMessage.error(response.message || '获取我的商品失败')
        return null
      }
    } catch (error) {
      console.error('获取我的商品错误:', error)
      ElMessage.error('获取我的商品失败，请检查网络连接')
      return null
    } finally {
      isLoading.value = false
    }
  }

  // 更新商品
  const updateGoods = async (goodsId, goodsData) => {
    try {
      isLoading.value = true
      const response = await goodsApi.updateGoods(goodsId, goodsData)
      
      if (response.code === 200) {
        ElMessage.success('商品更新成功')
        return true
      } else {
        ElMessage.error(response.message || '商品更新失败')
        return false
      }
    } catch (error) {
      console.error('更新商品错误:', error)
      ElMessage.error('商品更新失败，请检查网络连接')
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 删除商品
  const deleteGoods = async (goodsId) => {
    try {
      isLoading.value = true
      const response = await goodsApi.deleteGoods(goodsId)
      
      if (response.code === 200) {
        ElMessage.success('商品删除成功')
        // 从列表中移除已删除的商品
        myGoodsList.value = myGoodsList.value.filter(item => item.goodsId !== goodsId)
        return true
      } else {
        ElMessage.error(response.message || '商品删除失败')
        return false
      }
    } catch (error) {
      console.error('删除商品错误:', error)
      ElMessage.error('商品删除失败，请检查网络连接')
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 搜索商品
  const searchGoods = async (keyword) => {
    searchParams.value.keyword = keyword
    pagination.value.page = 1
    await getGoodsList()
  }

  // 筛选商品
  const filterGoods = async (filters) => {
    searchParams.value = { ...searchParams.value, ...filters }
    pagination.value.page = 1
    await getGoodsList()
  }

  // 重置搜索条件
  const resetSearch = () => {
    searchParams.value = {
      keyword: '',
      category: '',
      minPrice: '',
      maxPrice: '',
      condition: ''
    }
    pagination.value.page = 1
  }

  // 切换页码
  const changePage = async (page) => {
    pagination.value.page = page
    await getGoodsList()
  }

  return {
    // 状态
    goodsList,
    currentGoods,
    myGoodsList,
    categories,
    isLoading,
    pagination,
    searchParams,
    
    // 计算属性
    totalPages,
    
    // 方法
    getGoodsList,
    getGoodsDetail,
    publishGoods,
    getMyGoods,
    updateGoods,
    deleteGoods,
    searchGoods,
    filterGoods,
    resetSearch,
    changePage
  }
})